package cn.skcks.springboot04data.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

import static com.alibaba.druid.support.http.WebStatFilter.PARAM_NAME_EXCLUSIONS;

@Configuration
public class DruidConfig {

	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean
	public DataSource druidSource(){
		return new DruidDataSource();
	}

	// 后台监控
	// 因为 SpringBoot 内置了 Servlet 容器, 没有 web.xml, 故使用 ServletRegistrationBean 替代
	@Bean
	public ServletRegistrationBean<StatViewServlet> statViewServlet(){
		ServletRegistrationBean<StatViewServlet>  bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
		// 添加配置
		Map<String,String> initParameters = new HashMap<>();

		// 登录 用户账号,密码
		initParameters.put("loginUsername","admin");
		initParameters.put("loginPassword","123456");

		// 允许访问
		initParameters.put("allow","");

		// 禁止访问
		// initParameters.put("admin","127.0.0.1");

		// 设置初始化参数
		bean.setInitParameters(initParameters);
		return bean;
	}

	// Filter
	@Bean
	public  FilterRegistrationBean<WebStatFilter> webStatFilter(){
		FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter());

		// 需要过滤的请求
		Map<String,String> initParameters = new HashMap<>();

		// 排除的资源
		initParameters.put(PARAM_NAME_EXCLUSIONS,"*.png,*.jpg,*.jpeg,*.bmp,*.gif,*.js,*.css,/druid/*");

		// 设置初始化参数
		bean.setInitParameters(initParameters);
		return bean;
	}
}